package ua.kharkov.photo.controllers;

import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import ua.kharkov.photo.dal.UserRepository;
import ua.kharkov.photo.model.User;
import ua.kharkov.photo.model.UserToRegister;

@Controller
public class UserController extends AbstractController {

	private UserRepository userRepository;

	private static final Logger logger = LoggerFactory
			.getLogger(UserController.class);

	@Autowired
	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	@RequestMapping(value = "/login")
	public String loginUser(HttpServletResponse response, Model model,
			HttpServletRequest httpRequest, @ModelAttribute("user") User user) {

		Cookie[] cookies = httpRequest.getCookies();

		if (cookies == null || cookies[0].getValue().equals("")) {
			if (user.getUserName() != null && user.getPassword() != null) {
				if (userRepository.autorizeUser(user)) {

					logger.info(user.getUserName() + " logged");
					response.addCookie(new Cookie("loginedUserKey", DigestUtils
							.shaHex(user.getUserName() + user.getPassword())));
					return "redirect:gallery";
				} else {
					return "redirect:errors/incorrectpassword";
				}
			}
		} else {
			for (User u : userRepository.getAllUsers()) {
				if (cookies[0].getValue().equals(
						DigestUtils.shaHex(u.getUserName() + u.getPassword()))) {
					return "redirect:gallery";
				}
			}
		}

		return "login";
	}

	@RequestMapping(value = "/logout")
	public String logOut(HttpServletResponse response) {
		response.addCookie(new Cookie("loginedUserKey", null));
		return "redirect:login";
	}

	@RequestMapping(value = "/register")
	public String registerUser(
			@ModelAttribute("user-to-register") UserToRegister userToRegister,
			HttpServletResponse response) {

		if (userToRegister.getRegistrationUserName() != null
				&& userToRegister.getRegistrationPassword() != null
				&& userToRegister.getRegistrationConfirmedPassword() != null) {

			if (!Pattern.matches("[a-zA-Z0-9_]{4,15}",
					userToRegister.getRegistrationUserName())) {
				return "redirect:errors/incorrectinput";
			}

			if (!userToRegister.getRegistrationPassword().equals(
					userToRegister.getRegistrationConfirmedPassword())) {
				return "redirect:errors/passwordnotequals";
			}

			userRepository.registerUser(userToRegister);
			logger.info(userToRegister.getRegistrationUserName()
					+ " registered");
			response.addCookie(new Cookie("loginedUserKey", DigestUtils
					.shaHex(userToRegister.getRegistrationUserName()
							+ userToRegister.getRegistrationPassword())));

			return "redirect:gallery";
		}

		return "register";
	}
}
